import IconFont from '@/components/IconFont';
import CommonLoading from '@/components/CommonLoading';
import GoodsListModal from '@/pages/GoodsModule/combinationGoods/component/GoodsListModal'
import BatchInputModal from '@/pages/OrderModule/common/components/BatchInputModal';
import { CommonForm } from '@/pages/OrderModule/common/components/CommonForm';
import { CommonModal } from '@/pages/OrderModule/common/components/CommonModal';
import ResetStyle from '@/pages/OrderModule/common/components/ResetStyle';
import SubTitle from '@/pages/OrderModule/common/components/SubTitle';
import { Form, Input, Radio, Space, message, Modal, Button } from 'antd';
import React, { useState, useRef } from 'react';
import OrderAreaRadioGroup from '../../components/OrderAreaRadioGroup1';
import OrderNumberCount from '../../components/OrderNumberCount';
import { modifyGoodsViewOp, modifyGoodsOp } from '../../../../services';
import ConfirmPayModal from '../../components/ConfirmPayModal';
import Styles from './index.module.less'
import { formatAmount, cpText } from '@/utils/utils.jsx';

//字符串拆分为（商品编码*数量）list
const stringFormatArr = (str) => {
  return str ? str.replaceAll(' ', '').replaceAll('，', ',').split(',') : [];
}

const formatFunc = (str) => {
  let tips = false;
  if(str?.length){
    const allList = stringFormatArr(str);
    for(let i = 0; i < allList.length; i++){
      const arr = allList[i].split('*'), len = arr.length;

    }
  }
}

//覆盖操作
const combindStr = (oldValue, newValue) => {
  const obj = {}, oldArr = stringFormatArr(oldValue), newArr = stringFormatArr(newValue), allArr = [...oldArr, ...newArr];
  allArr.map(item=>{
    const arr = item.split('*');
    obj[arr[0]] = arr[1] || 1;
  })
  return Object.keys(obj).map(item=>item + "*" + obj[item]).join(',');
}
//覆盖操作
const combindStr2 = (oldValue, newValue) => {
  const obj = {}, oldArr = stringFormatArr(oldValue), newArr = stringFormatArr(newValue), allArr = [...oldArr, ...newArr];
  allArr.map(item=>{
    const arr = item.split('*');
    obj[arr[0]] = arr[1] || 1;
  })
  return Object.keys(obj).map(item=>item).join(',');
}

/** 批量修改商品 */
function UpdateGoodsModal(props) {
  const [form] = Form.useForm();

  const [loading, setLoading]=useState(false);
  const [showNumber, setShowNumber] = useState({});
  const [visible, setVisible] = useState(false);
  const filterIds = useRef(undefined);
  const stageParams = useRef({});
  const operatorType = useRef('add');

  const [amountObj, setAmountObj] = useState(null);

  const { orderList, searchForm, selectKeys, items = {} } = props;

  function handleOk() {
    if(!showNumber.total){
      return message.info('暂无可处理的订单！')
    }
    form.validateFields().then(async values =>{
      const { addSkuCodes, delSkuCodes, addStrategy } = values;
      setLoading(true);
      const params = {
        addStrategy,
        addSkuCodes: addSkuCodes ? stringFormatArr(addSkuCodes) : undefined,
        delSkuCodes: delSkuCodes ? stringFormatArr(delSkuCodes) : undefined,
        orderIds: selectKeys,
        'radio-group': undefined
      }
      const { data, success, msg } = await modifyGoodsViewOp(params);
      setLoading(false);
      if(success && data){
        if(!data.failCount) {
          return Modal.info({
            title: '修改商品提示',
            content: (
              <div>
                <div className='common-color9'>修改商品失败！</div>
                <div>失败原因：</div>
                {
                  data.msg.split('\n').map(v => {
                    return (
                      <div key={v}>{v}</div>
                    )
                  })
                }
                <div>{data.msg.replace}</div>
              </div>
            )
          })
        } else {
          return Modal.confirm({
            title: '修改商品提示',
            cancelText: '复制订单号',
            onCancel:(close) => {
              cpText(data.msg.replaceAll(';', '\n')) // 设置换行
              props.handleOk()
              close()
              // return Promise.resolve()
            },
            onOk() {
              props.handleOk()
            },
            content: (
              <div>
                <div className={Styles.flexwrap}>
                  <div>成功数：<span className={Styles['success']}>{data?.successNum}</span></div>
                  <div>失败数：<span className={Styles['fail']}>{data?.failCount}</span></div>
                </div>
                {/* <div>失败原因：</div> */}
                <div style={{fontSize: 12, margin: '5px 0'}}>以下订单，批量修改商品后，订单将会变成无商品，已跳过！</div>
                {
                  data.msg.split('\n').map(v => {
                    return (
                      <div key={v}>{v}</div>
                    )
                  })
                }
                {/* <Button onClick={() => {
                  cpText('M12323')
                }}>批量复制订单号</Button> */}
                <div>{data.msg.replace}</div>
              </div>
            )
          })
        }
        const { resultHandleType, payAmount, tradeNo } = data;
        stageParams.current = { ...params, tradeNo };
        if(typeof resultHandleType == 'object' || resultHandleType == 1){
          message.success(msg);
          props.handleOk?.();
          props.handleCancel?.();
        }else{
          setAmountObj(payAmount);
        }
      }
    })
  }

  //确定修改
  const handleSureModify = async (password) => {
    setLoading(true);
    const { msg, success} = await modifyGoodsOp({
      password,
      ...stageParams.current
    });
    setLoading(false);
    if(success){
      message.success(msg);
      props.handleOk?.();
      props.handleCancel?.();
    }
  }

  const orderAreaRadioProps = {
    searchForm,
    selectKeys,
    orderList,
    states: [10, 30],
    title:'仅限待审核、异常状态订单',
    updateShowNumer(obj, ids){
      filterIds.current = ids;
      setShowNumber(obj || {});
    }
  }

  const confirmPayModalProps = {
    amountObj,
    handleOk: handleSureModify,
    handleCancel(){
     setAmountObj(null);
    },
  }

  //批量添加
  const handleInputAddValue = (value) => {
    const oldValue = form.getFieldValue('addSkuCodes');
    const newCombineValue = combindStr(oldValue, value);
    form.setFieldValue('addSkuCodes', newCombineValue);
  }

  //批量删除
  const handleInputDeleteValue = (value) => {
    const oldArr = stringFormatArr(form.getFieldValue('delSkuCodes')),
    newArr = stringFormatArr(value),
    allArr = [...new Set([...oldArr, ...newArr])];
    form.setFieldValue('delSkuCodes', allArr.join(','));
  }

  const handleOpen = (typeValue) =>{
    operatorType.current = typeValue;
    setVisible(true)
  }

  const modalProps = {
    selectTitle: '选择商品',
    handleCancel() {
      setVisible(false);
    },
    onGoodsSkuListSelected(values) {
      if(operatorType.current == 'add'){
        handleInputAddValue(values.map(item=> `${item.skuCode}*${item.num || 1}`).join(','));
      }else{
        handleInputDeleteValue(values.map(item=> item.skuCode).join(','));
      }
    },
    destroyOnClose: true
};

  return (
    <CommonModal zIndex={222} title={{ title: '批量修改商品' }} open={true} width="530px" onOk={handleOk} onCancel={props.handleCancel}>
      <CommonForm
        formProps={{
          form,
          initialValues: {addStrategy: 1}
        }
      }
        columns={[
          {
            name: 'radio-group',
            slot: <OrderAreaRadioGroup {...orderAreaRadioProps} />,
          },
          {
            block: (
              <>
                <OrderNumberCount
                  data={[
                    { label: '待审核', value: showNumber[10], type: 'warning' },
                    { label: '异常', value: showNumber[30], type: 'error' },
                  ]}
                />
                <SubTitle symbol as="s2" title="商品修改方式" wrapStyle={{ marginTop: 16 }} />
              </>
            ),
          },
          {
            Component: Input,
            name: 'delSkuCodes',
            style: {
              marginTop: 12,
            },
            props: {
              suffix: (
                <Space>
                  {/* <GoodsSelectModal
                    setSelectedRows={(data) => {
                      return data;
                    }}
                    submitCallback={(val) => {
                      handleInputDeleteValue(val.map(item=> item.skuCode).join(','));
                    }}
                  > */}
                    <IconFont type="iconmodal-input" onClick={()=>handleOpen('delete')}/>
                  {/* </GoodsSelectModal> */}
                  <BatchInputModal
                    placeholder="删除指定商品，多个空格隔开"
                    onChange={val => handleInputDeleteValue(val)}
                  ></BatchInputModal>
                </Space>
              ),
              placeholder: '删除指定商品，多个逗号隔开',
            },
          },
          {
            Component: Input,
            name: 'addSkuCodes',
            style: {
              marginTop: 12,
            },
            props: {
              placeholder: '添加指定商品*数量，多个空格隔开',
              suffix: (
                <Space>
                  {/* <GoodsSelectModal
                    type={2}
                    setSelectedRows={(data) => {
                      return data;
                    }}
                    submitCallback={(val, obj) => {
                      handleInputAddValue(val.map(item=> `${item.skuCode}*${obj[item.id] || 1}`).join(','));
                    }}
                  > */}
                    <IconFont type="iconmodal-input" onClick={()=>handleOpen('add')}/>
                  {/* </GoodsSelectModal> */}
                  <BatchInputModal
                    placeholder="添加指定商品，多个逗号隔开"
                    onChange={val => handleInputAddValue(val)}
                  ></BatchInputModal>
                </Space>
              ),
            },
          },
          {
            block: <SubTitle symbol as="s2" title="添加商品规则" wrapStyle={{ marginTop: 16 }} />,
          },
          {
            name: 'addStrategy',
            slot: (
              <Radio.Group style={{ marginTop: 16 }}>
                <Space direction="vertical">
                  <Radio value={1}>订单已存在该商品则不添加</Radio>
                  <Radio value={2}>直接添加，如果商品重复，则另起一行添加</Radio>
                </Space>
              </Radio.Group>
            ),
          },
        ]}
      ></CommonForm>
      {amountObj && <ConfirmPayModal {...confirmPayModalProps} />}
      { visible && <GoodsListModal {...modalProps} />}
      <CommonLoading loading={loading} />
    </CommonModal>
  );
}

export default React.memo(ResetStyle(UpdateGoodsModal, { wrappers: ['rule-reset'] }));
